<template>
  <view class="radius-12 bg-white py-16 px-12 fs-14" @click="toDetail">
    <view class="flex justify-between item-center mb-8">
      <text class="text-color-hint fs-14">{{data.createTime}}</text>
      <text class="font-semibold" :style="`color:${activeStateDict[data.activeState].color}`">{{activeStateDict[data.activeState].text}}</text>
    </view>
    <view class="mb-12" style="position: relative;">
      <view v-if="data.hideLink === 1" class="hide-tip">隐藏活动</view>
      <!--
			<template v-if="photos.length > 1">
				<block v-for="(item, i) in photos.filter((_,i) => i < 3)" :key="item">
					<video v-if="isVideoFile(item)" class="overflow-hidden radius-8" :class="i===2?'':'mr-6'" style="width:calc((100% - 12px)/3);height:105px;" :src="item" :controls="false"></video>
					<image v-else class="overflow-hidden radius-8" :class="i===2?'':'mr-6'" mode="aspectFill" style="width:calc((100% - 12px)/3);height:105px;" :src="item"></image>
				</block>
			</template>
			<block v-else-if="photos.length === 1">
				<video v-if="isVideoFile(photos[0])" class="radius-8 w-full overflow-hidden" style="height:105px;" :src="photos[0]"></video>
				<image v-else class="radius-8 w-full overflow-hidden" style="height:105px;" mode="aspectFill" :src="photos[0]"></image>
			</block>
			-->
      <!-- 活动列表默认显示单图（显示活动图片首张图片）-->
      <image class="radius-8 w-full overflow-hidden" style="height:150px;" mode="aspectFill" :src="coverPicture"></image>
    </view>
    <view class="mb-8 two-lines-ellipsis">
      <!-- <sign-up-tag v-if="isSignUp" class="mr-8" /> -->
      <tag v-if="data.promotionLabel" class="mr-4">{{ data.promotionLabel }}</tag>
      <text class="font-semibold align-middle">{{data.activeTitle}}</text>
    </view>
    <view class="flex item-center mb-12">
      <text class="color-primary">¥</text><text class="color-primary fs-21 font-semibold mr-8">{{numberFormat(data.activePrice)}}</text>
      <newcomer-coupon-tag v-if="data.activeRedPacket" :price="data.activeRedPacket.firstRedPacketAmt" class="mr-10" />
      <template v-if="data.activeDiscount && data.activeDiscount.length <= 2">
        <full-discount-tag v-for="(item,index) in data.activeDiscount" :key="index" :data="item" class="mr-10" />
      </template>
      <!--
			<view v-if="data.commissionAmt" class="flex item-center">
				<image class="size-16 mr-2" src="@/static/svg/activity/icon-commission.svg"></image>
				<text class="color-primary fs-12">佣金</text>
				<text class="color-primary fs-12">¥{{data.commissionAmt}}</text>
			</view>
			<view v-else-if="data.commissionRate" class="flex item-center">
				<image class="size-16 mr-2" src="@/static/svg/activity/icon-commission.svg"></image>
				<text class="color-primary fs-12">佣金</text>
				<text class="color-primary fs-12">{{data.commissionRate}}%</text>
			</view>
			-->
    </view>
    <view v-if="data.activeStepPrices && data.activeStepPrices.length" class="mb-12">
      <sign-up-number-tag v-for="(item,index) in data.activeStepPrices" :key="index" :number="item.enrollNum" :price="numberFormat(data.activePrice - item.enrollPrice,2)" :type="2" class="mr-8" />
    </view>
    <view v-if="data.activeDiscount && data.activeDiscount.length === 3" class="mb-12">
      <full-discount-tag v-for="(item,index) in data.activeDiscount" :key="index" :data="item" class="mr-10" />
    </view>
    <view v-if="data.browseNum||data.buyNum||data.agentState===2" class="py-4 mb-12">
      <view class="flex item-center justify-between">
        <!-- 只设置佣金只显示佣金 -->
        <view class="inline-flex item-center px-8 py-2 fs-12 radius-14 bg-pale-yellow border-secondary-warning" v-if="data.commissionAmt || data.agentShareCount">
          <text v-if="data.commissionAmt">佣金: <text class="color-primary fs-14">¥{{data.commissionAmt}}</text></text>
          <text v-if="data.agentShareCount" class="ml-12 color-secondary-warning">{{ data.agentShareCount }}位经纪人正在推广</text>
          <!-- <text v-else-if="data.defaultCommissionType==2" class="color-primary fs-12">{{data.commissionRate}}%</text> -->
        </view>
        <view v-else></view>
        <!-- 设置了权益或者都设置显示查看 -->
        <view v-if="data.otherEquity" class="flex item-center ml-6" @click.stop="showEquity">
          <image class="size-16 mr-2" src="@/static/image/icon-value-share.png"></image>
          <text class="color-primary text-underline fs-12">查看权益</text>
        </view>
      </view>
      <view class="inline-flex item-center px-8 py-4 radius-20 bg-default mt-8" style="color:#858585;">
        <text>{{data.browseNum + data.virtualSaleNum * data.virtualNum}}人查看</text>
        <text>｜</text>
        <text>已售{{data.buyNum + (data.virtualSaleNum?data.virtualSaleNum:0)}}份</text>
      </view>
    </view>
    <view class="flex justify-end item-center">
      <view class="flex center px-8 py-4 radius-8 fs-12 mr-8 color-secondary-success border-secondary-success" @click.stop="copyLink">
        <image class="size-16 mr-2" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/link.png"></image>
        <text>复制链接</text>
      </view>
      <!-- <view v-if="[3,4].includes(data.activeState)" class="flex center px-8 py-4 radius-8 ml-8 fs-12" style="border:1px solid #999;color:#999;" @click.stop="toOrder">
				<image class="size-16 mr-4" src="@/static/svg/icon-order.svg"></image>
				<text>订单管理</text>
			</view>
			<view class="border-primary flex center px-8 py-4 radius-8 ml-8 fs-12 color-primary" @click.stop="toDelete">
				<image class="size-16 mr-4" src="@/static/svg/icon-delete.svg"></image>
				<text>删除</text>
			</view>
			<view v-if="[1,2,3].includes(data.activeState)" class="border-secondary-warning flex center px-8 py-4 radius-8 ml-8 fs-12 color-secondary-warning" @click.stop="toEdit">
				<image class="size-16 mr-4" src="@/static/svg/icon-edit.svg"></image>
				<text>编辑</text>
			</view>
			<view v-if="data.activeState===1" class="border-secondary-success flex center px-8 py-4 radius-8 ml-8 fs-12 color-secondary-success" @click.stop="toPublish">
				<image class="size-16 mr-4" src="@/static/svg/icon-publish.svg"></image>
				<text>发布</text>
			</view> -->
      <view class="border-secondary-info flex center px-8 py-4 radius-8 fs-12 color-secondary-info" @click.stop="manage">
        <image class="size-16 mr-4" src="@/static/svg/icon-manage.svg"></image>
        <text>活动管理</text>
      </view>
      <image v-if="data.activeState===3 || data.activeState===2" class="size-24 ml-12" src="@/static/svg/icon-relay.svg" @click.stop="toShare"></image>
    </view>
    <share-activity :id="data.id" :show="showSharePopup" @onClose="showSharePopup=false" :options="{groupBuyLabel:data.promotionLabel}" />
    <EquityDialog ref="equityDialogRef" :commissionAmt="data.commissionAmt" :commissionRate="data.commissionRate" :otherEquity="data.otherEquity" :defaultCommissionType="data.defaultCommissionType" />
    <view @click.stop>
      <uni-popup ref="popup" type="bottom" :safe-area="false">
        <view class="relative flex-col">
          <view class="bg-white flex-col" style="border-radius:12px 12px 0 0;">
            <template v-if="[3,4].includes(data.activeState)">
              <view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toOrder">查看活动订单</view>
              <view class="h-1 bg-default"></view>
            </template>
            <template v-if="[1,2,3].includes(data.activeState)">
              <view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toEdit">修改活动信息</view>
              <view class="h-1 bg-default"></view>
            </template>
            <template v-if="data.activeState===1">
              <view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toPublish">发布活动</view>
              <view class="h-1 bg-default"></view>
            </template>
            <!-- <template v-if="[2,3].includes(data.activeState)">
							<view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toPublish">下架活动</view>
							<view class="h-1 bg-default"></view>
						</template> -->
            <template v-if="data.agentState===2 && data.activeState!==2 && data.activeState!==1">
              <view class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toDistribution">查看分销排行</view>
              <view class="h-1 bg-default"></view>
            </template>
            <view class="h-1 bg-default"></view>
            <view v-if="data.activeState===3" class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toShelf">下架活动</view>
            <view v-else class="mt-20 mb-16 leading-22 text-center text-color-regular fs-16 font-medium" @click.stop="toDelete">删除活动</view>
            <view class="h-13 bg-default"></view>
            <view class="mt-20 mb-16 leading-22 text-center c9 fs-16 font-medium" @click.stop="close">取消</view>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, watchEffect } from 'vue'
import { businessActiveDeleteApi, businessActiveDownApi } from '@/api/business.js'
import { generateShortLinkApi } from '@/api/activity.js'
import { useActivity } from '@/hooks/useActivity.js'
import { isVideoFile, numberFormat, modelShowToastAsync, reformatDatetime } from '@/utils/index.js'
import EquityDialog from '@/components/equity-dialog/equity-dialog.vue'
import FullDiscountTag from '@/components/full-discount-tag/full-discount-tag.vue'
import Tag from '@/components/tag/tag.vue'

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
})

const emits = defineEmits(['onDelete'])

const { isSignUp, photos, coverPicture, updateActivityInfo } = useActivity()

watchEffect(() => {
  updateActivityInfo(props.data)
})

const activeStateDict = {
  1: {
    text: '未发布',
    color: '#FCB513',
  },
  2: {
    text: '未开始', // 已发布，活动未开始
    color: '#00AEFF',
  },
  3: {
    text: '进行中',
    color: '#16BE62',
  },
  4: {
    text: '已结束',
    color: 'rgba(51, 51, 51, 0.60)',
  },
}

const editAble = computed(() => data.activeState === 1)

const equityDialogRef = ref(null)
const showEquity = () => {
  equityDialogRef.value && equityDialogRef.value.showDialog(true)
}

const toEdit = () => {
  const url = props.data.promotionType === 'GROUP_BUY'
    ? `/pagesG/publish/create-group-buy-activity?id=${props.data.id}&from=myactivity`
    : `/pagesG/publish/create-activity?id=${props.data.id}&from=myactivity`;
  uni.navigateTo({
    url
  })
}

const toDetail = () => {
  const url = props.data.promotionType === 'GROUP_BUY'
    ? `/pagesB/my-activity/activity-group-buy-detail?id=${props.data.id}&_from=BMyActivityItem`
    : `/pagesB/my-activity/activity-detail?id=${props.data.id}&_from=BMyActivityItem`;
  uni.navigateTo({
    url,
    // url: `/pagesB/activity/activity?id=${props.data.id}`
    events: {
      onDelete() {
        console.log('删除')
      }
    }
  })
}

// 分销排行
const toDistribution = () => {
  uni.navigateTo({
    url: `/pagesG/distribution/distribution-info?id=${props.data.id}`
  })
}

const toOrder = () => {
  const url = props.data.promotionType === 'GROUP_BUY'
    ? `/pagesB/my-activity/activity-group-buy-order?id=${props.data.id}&_from=BMyActivityItem`
    : `/pagesB/my-activity/activity-order?id=${props.data.id}&_from=BMyActivityItem`;
  uni.navigateTo({
    url,
    events: {
      onUpdate() {
        console.log('状态更新')
      }
    }
  })
}

const toDelete = async () => {
  const canDel = !props.data.validEndTime || (new Date() - new Date(reformatDatetime(props.data.validEndTime))) > 0 || [1, 2].includes(props.data.activeState);
  if (!canDel) {
    await modelShowToastAsync({ content: '核销有效期未结束，不能删除！', confirmText: '知道了', confirmColor: '#FA4543', showCancel: false });
    return;
  }
  uni.showModal({
    confirmColor: '#FA4543',
    confirmText: '确定删除',
    content: '删除后无法查看、导出该活动订单，确定删除吗？',
    success: (res) => {
      if (res.confirm) {
        businessActiveDeleteApi(props.data.id).then(res => {
          uni.showToast({
            title: '删除成功',
            icon: 'none'
          })
          close()
          emits('onDelete')
        })
      }
    }
  })
}

const toShelf = () => {
  uni.showModal({
    content: '确定下架该活动？',
    success: (res) => {
      if (res.confirm) {
        businessActiveDownApi(props.data.id).then(res => {
          uni.showToast({
            title: '下架成功',
            icon: 'none'
          })
          close()
          emits('onDelete')
        })
      }
    }
  })
}

const toPublish = () => {
  const url = props.data.promotionType === 'GROUP_BUY'
    ? `/pagesG/publish/create-group-buy-activity?id=${props.data.id}&from=myactivity`
    : `/pagesG/publish/create-activity?id=${props.data.id}&from=myactivity`;
  uni.navigateTo({
    url
  })
}
const popup = ref(false)
const manage = () => {
  popup.value && popup.value.open()
}
const close = () => {
  popup.value && popup.value.close()
}

const showSharePopup = ref(false)
const toShare = () => {
  showSharePopup.value = true
}

const copyLink = async () => {
  const url = props.data.promotionType === 'GROUP_BUY'
    ? `pagesB/activity/activity-group-buy?id=${props.data.id}`
    : `pagesB/activity/activity?id=${props.data.id}`;
  const data = await generateShortLinkApi({ 'pageUrl': url }).catch(err => null);
  if (!data) {
    uni.showToast({ title: '链接获取失败', icon: 'none' });
    return;
  }
  uni.setClipboardData({
    data,
    success: () => {
      // 先隐藏默认的
      uni.hideToast();
      // 再显示自己的
      uni.showToast({ title: '链接复制成功', icon: 'none' });
    },
  })
};
</script>
<style scoped lang="scss">
.hide-tip {
  z-index: 1;
  padding: 2px 8px;
  font-size: 12px;
  color: #333;
  position: absolute;
  top: 0;
  left: 0;
  background: #fbdbb0;
  border-radius: 8px 0px 8px 0px;
}
</style>